package com.alogic.xscript;

import com.alogic.xscript.doc.XsObject;
import com.alogic.xscript.doc.json.JsonObject;
import com.anysoft.util.Properties;
import org.apache.commons.lang3.StringUtils;
import org.w3c.dom.Element;
import java.util.HashMap;

/**
 * 扩展tag插件
 *
 * @since 1.6.12.42 [20190911]
 */
public abstract class ExtensionTag extends AbstractLogiclet {
    protected String src;
    protected Logiclet script = null;

    public ExtensionTag(String tag, Logiclet p) {
        super(tag, p);
    }

    public ExtensionTag(String tag, Logiclet p, String src){
        super(tag, p);
        this.src = src;
    }

    @Override
    public void configure(Element e, Properties p) {
        super.configure(e, p);
        if (StringUtils.isNotEmpty(src)) {
            try {
                script = Script.create(src, p,this);
            } catch (Exception ex) {
                log("Can not create script from " + src);
            }
        }
    }

    @Override
    protected void onExecute(XsObject root, XsObject current, LogicletContext ctx, ExecuteWatcher watcher) {
        if (script == null){
            log(String.format("[%s] Script is null ,ignored..",this.getXmlTag()),"warnning");
            return ;
        }
        LogicletContext childCtx = new LogicletContext(ctx);
        XsObject doc = new JsonObject("root",new HashMap<String,Object>());
        onStart(ctx,childCtx);
        script.execute(doc,doc, childCtx, null);
        onEnd(ctx,childCtx);
    }

    abstract protected void onStart(LogicletContext ctx, LogicletContext childCtx);

    abstract protected void onEnd(LogicletContext ctx, LogicletContext childCtx);
}
